from django.shortcuts import render
from django.views import View
from apps.user.models import User, Address
from django.http import JsonResponse, HttpResponseBadRequest
import json
import re
from django_redis import get_redis_connection
from django.contrib.auth import login, authenticate, logout
from utils.views import LoginRequiredJsonMixin
import logging
from django.conf import settings
from apps.user.utils import dumps_token, loads_token
from celery_tasks.emails.tasks import send_email
logger = logging.getLogger('django')
# Create your views here.






class UserPasswordUpdateView(LoginRequiredJsonMixin, View):
    def put(self, request):
        # 接受参数
        password_dict = json.loads(request.body.decode())
        old_password = password_dict.get('old_password')
        new_password = password_dict.get('new_password')
        new_password2 = password_dict.get('new_password2')

        # 效验参数
        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400,
                                'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400,
                                'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,
                                'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400,
                                'errmsg': '两次输入密码不一致'})



        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('失败')
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})


# ======================================================================================================

# 添加title
class UserAddressTitleView(LoginRequiredJsonMixin, View):
    def put(self, request, address_id):
        title_b = json.loads(request.body.decode())
        title = title_b.get('title')

        try:
            Address.objects.filter(id=address_id).update(title=title)
        except Address.DoesNotExist as e:
            logger.error(e)
            return HttpResponseBadRequest('添加失败')
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})


# ===============================================================================================================

# 设置默认地址
class UserAddressDefaultView(LoginRequiredJsonMixin, View):
    def put(self, request, address_id):
        try:
            User.objects.filter(id=request.user.id).update(default_address_id=address_id)
        except User.DoesNotExist as e:
            logger.error(e)
            return HttpResponseBadRequest('修改错误')
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})



# =================================================================================================================

# 地址增删改
class UserAddressModifyView(View):
    def delete(self, request, address_id):
        # 通过用户传来的address_id删除地址
        try:
            Address.objects.filter(id=address_id).delete()
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('删除失败')
        return JsonResponse({'code': 0,
                             'errmsg': 'ok'})

    def put(self, request, address_id):
        # 拿到修改后的数据
        json_dict = json.loads(request.body.decode())

        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 效验信息
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400,
                                    'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,
                                    'errmsg': '参数email有误'})
        # 用address_id查询数据库对象执行update
        try:
            address = Address.objects.filter(id=address_id)
            address.update(title=receiver,
                           receiver=receiver,
                           province=province_id,
                           city=city_id,
                           district=district_id,
                           place=place,
                           mobile=mobile,
                           tel=tel,
                           email=email
                           )
        except Address.DoesNotExist as e:
            logger.error(e)
            return HttpResponseBadRequest('修改失败')
        # 返回响应

        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'address': address_dict})






# ===================================================================================
# 新增地址
class UserAddressCreateView(LoginRequiredJsonMixin, View):
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 效验
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseBadRequest('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseBadRequest('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseBadRequest('参数email有误')

        # 保存数据
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email)
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('no')
        if not request.user.default_address_id:
            request.user.default_address_id = address
            request.user.save()
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'address': address_dict})
# ==========================================================================================

# 展示地址
class UserAddressLookView(LoginRequiredJsonMixin, View):
    def get(self, request):
        # 获取所有的地址:
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)
        # 创建空的列表
        address_dict_list = []

        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            if request.user.default_address_id == address.id:
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        default_id = request.user.default_address_id

        return JsonResponse({'code': 0,
                            'errmsg': 'ok',
                            'addresses': address_dict_list,
                            'default_address_id': default_id})




# =============================================================================================
# 用户邮箱发送

class UserEmailAddView(View):
    def put(self, request):
        # 拿到email
        email_b = json.loads(request.body.decode())
        email = email_b.get('email')

        # 验证
        if not email:
            return JsonResponse({'code': 400,
                                'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,
                                'errmsg': '参数email有误'})
        # 保存
        try:
            request.user.email=email
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400,
                                'errmsg': '参数有误'})

        # 发邮件
        # 生成token_url
        token = {
            'user_id': request.user.id,
            'email': request.user.email
        }
        token_url = dumps_token(token)
        token_urls = settings.EMAIL_VERIFY_URL + '?token=' + token_url

        send_email.delay(email, token_urls)

        return JsonResponse({'code': 0,
                            'errmsg': 'ok'})

# =====================================================================================================
# 用户邮箱验证
class UserEmailCleckView(View):
    def put(self, request):
        # 拿到token
        token_b = request.GET.get('token')
        # 解码
        token_dict = loads_token(token_b)

        if not token_dict:
            return JsonResponse({'code': 400,
                                'errmsg': 'no token'})
        user_id = token_dict.get('user_id')
        email = token_dict.get('email')
        if not all([user_id, email]):
            return JsonResponse({'code': 400,
                                'errmsg': 'no'})
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return JsonResponse({'code': 400,
                            'errmsg': 'no'})

        # 激活
        try:
            user.email_active = True
            user.save()

        except user.DoesNotExist:
            return JsonResponse({'code': 400,
                                'errmsg': 'no'})
        return JsonResponse({'code': 0,
                            'errmsg': 'ok'})


# =========================================================================================

# 用户中心用户数据
class UserInfoView(LoginRequiredJsonMixin, View):
    def get(self, request):
        info_data = {
            'username': request.user.username,
            'mobile': request.user.modile,
            'password': request.user.password,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'info_data': info_data})

# ===========================================================================================
# 用户退出
class UserLogoutView(View):
    def delete(self, request):
        # 删除session
        logout(request)

        # 删除cookie中的username
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok'})
        response.delete_cookie('username')

        # 返回
        return response

# ==========================================================================================
# 用户登录
class UserLoginView(View):
    def post(self, request):
        # 拿到参数
        userinfo_dict = json.loads(request.body.decode())
        username = userinfo_dict.get('username')
        password = userinfo_dict.get('password')
        remember = userinfo_dict.get('remembered')

        # 效验参数
        if not all([username, password]):
            return JsonResponse({'code': 400,
                                 'errmsg': '参数缺失',
                                 })

        # 判断是手机号还是用户名
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'modile'

        # 查询用户
        user = authenticate(username=username,
                            password=password)
        if user == None:
            return JsonResponse({'code': 400,
                                 'errmsg': '用户不存在',
                                 })

        # 状态保持前端显示用户名
        login(request, user)
        if remember == True:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)
        response = JsonResponse({'code': 0,
                                 'errmsg': 'ok',
                                 })
        response.set_cookie('username', username, max_age=4000)

        # 返回数据
        return response

# ============================================================================================
# 用户名
class UsernameCount(View):
    def get(self, request, username):
        name_count = User.objects.filter(username=username).count()
        if name_count == 0:
            return JsonResponse({'code': 0,
                                 'errmsg': 'ok',
                                 'count': name_count})
        return JsonResponse({'code': 200,
                             'errmsg': '用户名以存在',
                             'count': name_count})

# ===================================================================================================

# 手机号
class MobileCount(View):
    def get(self, request, mobile):
        mobile_count = User.objects.filter(modile=mobile).count()
        if mobile_count == 0:
            return JsonResponse({'code': 0,
                                 'errmsg': 'ok',
                                 'count': mobile_count})
        return JsonResponse({'code': 200,
                             'errmsg': '手机号以存在',
                             'count': mobile_count})


# =================================================================================================
# 用户注册
class UserRegisterView(View):
    def post(self, request):
        # 拿到数据
        # 用户注册完善
        redis_conn = get_redis_connection('code')

        user_info_json = request.body.decode()
        user_info_dict = json.loads(user_info_json)

        username = user_info_dict.get('username')
        password = user_info_dict.get('password')
        password2 = user_info_dict.get('password2')
        mobile = user_info_dict.get('mobile')
        sms_code = user_info_dict.get('sms_code')
        allow = user_info_dict.get('allow')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        # 效验数据
        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': 200,
                                 'errmsg': '数据不全',
                                 })
        if sms_code_server == None:
            return JsonResponse({'code': 200,
                                 'errmsg': '短信验证码失效',
                                 })
        sms_code_server = sms_code_server.decode()
        if sms_code_server != sms_code:
            return JsonResponse({'code': 200,
                                 'errmsg': '验证码不正确',
                                 })

        if not re.match('[a-zA-Z0-9_-]{5,20}', username):
            return JsonResponse({'code': 200,
                                 'errmsg': '用户名不正确',
                                 })
        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({'code': 200,
                                 'errmsg': '手机号不正确',
                                 })
        if not re.match('[a-zA-Z0-9_-]{8,20}', password):
            return JsonResponse({'code': 200,
                                 'errmsg': '密码不正确',
                                 })
        if password2 != password:
            return JsonResponse({'code': 200,
                                 'errmsg': '密码不匹配',
                                 })
        if allow != True:
            return JsonResponse({'code': 200,
                                 'errmsg': '用户没有签合同',
                                 })

        # 效验后动作
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            modile=mobile)
        except Exception as e:
            return JsonResponse({'code': 200,
                                 'errmsg': e,
                                 })
        login(request, user)
        return JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             })